package com.zlkj.pro.core.util;


import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 函数转换工具
 *
 * @author 孙铭泽
 * @date 2020-12-16
 * @time 17:23
 **/
public class FunctionUtil {

	private FunctionUtil() {
		throw new IllegalStateException();
	}

	/**
	 * 根据某字段转成集合
	 */
	public static <D, V> List<V> toList(List<D> list, Function<D, V> function) {
		return Optional.ofNullable(list)
				.orElse(Collections.emptyList())
				.stream()
				.map(function)
				.collect(Collectors.toList());
	}

	/**
	 * @param list     集合
	 * @param function key
	 * @return map
	 */
	public static <K, V> Map<K, V> toMap(List<V> list, Function<V, K> function) {
		return Optional.ofNullable(list)
				.orElse(Collections.emptyList()).stream()
				.collect(Collectors.toMap(function, Function.identity(), (k1, k2) -> k1));
	}


	/**
	 * 集合按照指定字段去重
	 *
	 * @param list     集合
	 * @param function 去重字段
	 * @return 结合
	 */
	public static <T> List<T> distinct(List<T> list, Function<T, Object> function) {
		return Optional.ofNullable(list)
				.orElse(Collections.emptyList()).stream()
				.filter(c -> {
					Map<Object, Boolean> seen = new ConcurrentHashMap<>();
					return Objects.isNull(seen.putIfAbsent(function.apply(c), Boolean.TRUE));
				})
				.collect(Collectors.toList());
	}

}
